1 /** 2 The following examples come from 3 $(LINK http://zetcode.com/db/sqlite/constraints/). 4 Even though it is a SQLite tutorial the point is to show how to use this package 5 which does not have to be just SQLite. 6 */ 7 module test.examples_check_constraint; 8 9 version(D_Ddoc) 10 { 11 /// 12 class BlankClassSoDocsWillBeGenerated { } 13 } 14 15 /** 16 This example is for the CHECK constraint. The table 17 in SQL can be created by 18 $(D $(D $(D sql 19 CREATE TABLE Orders 20 ( 21 Id INTEGER NOT NULL PRIMARY KEY, 22 OrderPrice INTEGER CHECK(OrderPrice > 0), 23 Customer TEXT 24 ); 25 26 ))) 27 */ 28 unittest 29 { 30 import db_constraints; 31 32 class Order 33 { 34 private int _Id; 35 // marking Id with not null and primary key 36 @NotNull @PrimaryKeyColumn 37 @property int Id() 38 { 39 return _Id; 40 } 41 @property void Id(int value) 42 { 43 setter(_Id, value); 44 } 45 46 private int _OrderPrice; 47 // marking OrderPrice with a check constraint 48 // that makes sure OrderPrice is greater than 0 49 @CheckConstraint!(a => a > 0) 50 @property int OrderPrice() 51 { 52 return _OrderPrice; 53 } 54 @property void OrderPrice(int value) 55 { 56 setter(_OrderPrice, value); 57 } 58 59 private string _Customer; 60 @property string Customer() 61 { 62 return _Customer; 63 } 64 @property void Customer(string value) 65 { 66 setter(_Customer, value); 67 } 68 69 this(int Id_, int OrderPrice_, string Customer_) 70 { 71 this._Id = Id_; 72 this._OrderPrice = OrderPrice_; 73 this._Customer = Customer_; 74 initializeKeyedItem(); 75 } 76 77 mixin KeyedItem!(); 78 } 79 80 import std.exception : assertNotThrown, assertThrown; 81 82 // throws because -10 is less than 0 and the check constraint does 83 // not allow that. 84 assertThrown!CheckConstraintException(new Order(1, -10, "Johnson")); 85 86 // we can create a new order that will not error 87 auto i = new Order(1, 10, "Johnson"); 88 // if we change the order price to another value still greater than 89 // 0 we should not get an error 90 assertNotThrown!CheckConstraintException(i.OrderPrice = 9); 91 assert(i.OrderPrice == 9); 92 93 // but we will get an error if we try to change it to 94 // something below 0 again 95 assertThrown!CheckConstraintException(i.OrderPrice = -1); 96 }